package com.laicunba.service.jzh.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.constant.GloabConstant;
import com.laicunba.pojo.JzhRechargeOrderDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.UserService;
import com.laicunba.service.impl.BaseServiceImpl;
import com.laicunba.service.jzh.JzhAccountService;
import com.laicunba.service.jzh.JzhRechargeOrderService;
import com.laicunba.service.jzh.SecurityUtils;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.StringUtil;

@Service
public class JzhRechargeOrderServiceImpl extends BaseServiceImpl implements JzhRechargeOrderService {
	private static final Logger LOG = Logger.getLogger(JzhRechargeOrderServiceImpl.class);
	private static final char SPLIT_CHAR = '|';
	@Autowired
	private UserService userService;
	@Autowired
	private JzhAccountService jzhAccountService;

	@Transactional
	@Override
	public Result createNewOrder(UserDO userDO, Long seq, BigDecimal amt) {

		Result result = new Result();

		JzhRechargeOrderDO jzhRechargeOrderDO = new JzhRechargeOrderDO();
		String orderId = Long.toString(System.currentTimeMillis()) + StringUtil.randomNumber(7) + String.format("%08d", seq);
		jzhRechargeOrderDO.setId(orderId);
		jzhRechargeOrderDO.setMchntTxnSsn(orderId);
		jzhRechargeOrderDO.setPay(false);
		jzhRechargeOrderDO.setAmt(amt.multiply(BigDecimal.valueOf(100)).intValue());
		jzhRechargeOrderDO.setLoginId(userDO.getMobile());
		jzhRechargeOrderDO.setUserId(userDO.getId());

		String backNotify = GloabConstant.H5_PATH + "/h5/jzh_back_notify.htm";
		String pageNotify = GloabConstant.H5_PATH + "/h5/jzh_page_notify.htm";
		StringBuilder signBuilder = new StringBuilder();
		signBuilder.append(Integer.toString(jzhRechargeOrderDO.getAmt())).append(SPLIT_CHAR);
		signBuilder.append(backNotify).append(SPLIT_CHAR);
		signBuilder.append(jzhRechargeOrderDO.getLoginId()).append(SPLIT_CHAR);
		signBuilder.append(GloabConstant.JZH_MCHNT_CD).append(SPLIT_CHAR);
		signBuilder.append(jzhRechargeOrderDO.getMchntTxnSsn()).append(SPLIT_CHAR);
		signBuilder.append(pageNotify);
		result.setOrder(jzhRechargeOrderDO);
		result.setBackNotify(backNotify);
		result.setPageNotify(pageNotify);
		result.setSignature(SecurityUtils.sign(signBuilder.toString()));
		AssertUtil.assertTrue(create(jzhRechargeOrderDO), "CREATE_JZH_RECHARGE_ORDER_DO_FAIL");
		return result;
	}

	@Override
	public boolean verifyFromJzhServer(PayResult result) {
		StringBuilder signBuilder = new StringBuilder();
		signBuilder.append(result.getAmt()).append(SPLIT_CHAR);
		signBuilder.append(result.getLoginId()).append(SPLIT_CHAR);
		signBuilder.append(result.getMchntCd()).append(SPLIT_CHAR);
		signBuilder.append(result.getMcnntTxnSsn()).append(SPLIT_CHAR);
		signBuilder.append(result.getRespCode());
		return SecurityUtils.verifySign(signBuilder.toString(), result.getSignature());
	}

	@Transactional
	@Override
	public boolean onPaySuccess(PayResult result) {
		AssertUtil.assertNotNull(result, "RESULT_IS_NULL");
		AssertUtil.assertTrue("0000".equals(result.getRespCode()), "NOT_PAY_SUCCESS");
		AssertUtil.assertTrue(GloabConstant.JZH_MCHNT_CD.equals(result.getMchntCd()), "MCHNT_CD_NOT_MATCH");
		JzhRechargeOrderDO orderDO = get(JzhRechargeOrderDO.class, result.getMcnntTxnSsn());
		AssertUtil.assertNotNull(orderDO, "ORDER_NOT_EXIST");

		UserDO userDO = userService.get(UserDO.class, orderDO.getUserId());
		AssertUtil.assertNotNull(userDO, "USER_NOT_EXIST");
		AssertUtil.assertTrue(userDO.getMobile().equals(result.getLoginId()), "LOGIN_ID_NOT_MATCH");

		if (orderDO.isPay()) {
			return true;
		}
		AssertUtil.assertTrue(result.getAmt() == orderDO.getAmt(), "AMT_NOT_MATCH");
		AssertUtil.assertTrue(updateDao.update("JZH_RECHARGE_ORDER.updatePaySuccess", orderDO.getId()) == 1, "UPDATE_PAY_STATUS_FAIL");

		BigDecimal balance = jzhAccountService.add(userDO.getId(), BigDecimal.valueOf(result.getAmt()).divide(BigDecimal.valueOf(100)), "recharge_" + result.getMcnntTxnSsn(), "recharge", "充值");
		AssertUtil.assertNotNull(balance, "ADD_BALANCE_FAIL");
		return true;
	}
	
	@Override
	public List<JzhRechargeOrderDO> findJzhRechargeList(String userId, int limit, int offset) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userId", userId);
		param.put("limit", limit);
		param.put("offset", offset);
		return queryDao.selectList("JZH_RECHARGE_ORDER.findJzhRechargeList", param);
	}
}
